<template>
    <el-upload :action="action" :headers="headers" :limit="1" :accept="accept" :on-success="handSuccess" :before-upload="beforeUpload">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">请上传文件</div>
    </el-upload>
</template>

<script>
export default {
    data() {
        return {
            headers: {
                Authorization: '',
            },
        }
    },
    props: {
        action: {
            type: String,
            default() {
                return ''
            },
        },
        accept: {
            type: String,
            default() {
                return ''
            },
        },
    },
    methods: {
        beforeUpload(file) {
            let b = false
            let list = this.accept.split('/')
            list.forEach((item) => {
                if (file.name.includes(item)) {
                    b = true
                }
            })
            if (b) {
                return true
            } else {
                this.$message.error('文件格式不正确')
                return false
            }
        },
        handSuccess(file) {
            if (file.code === 0) {
                this.$emit('filepath', file.data)
            } else {
                this.$message.error('文件上传失败')
            }
        },
    },
    created() {
        let token = localStorage.getItem('token')
        this.headers.Authorization = token
    },
}
</script>
